package com.lemon.reggie.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lemon.reggie.common.BusinessException;
import com.lemon.reggie.common.R;
import com.lemon.reggie.common.SystemCode;
import com.lemon.reggie.pojo.dto.SendMsgDTO;
import com.lemon.reggie.pojo.dto.UserLoginDTO;
import com.lemon.reggie.pojo.entity.User;
import com.lemon.reggie.service.UserService;
import com.lemon.reggie.utils.RegexValidateUtils;
import com.lemon.reggie.utils.SMSUtils;
import com.lemon.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author Lemon
 * @since 2022-05-23
 */
@RestController
@RequestMapping("/user")
@Validated
@Slf4j
public class UserController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UserService userService;

    @RequestMapping("/hello")
    public R<String> hello() {
        return R.success("搭建项目成功！");
    }

    @PostMapping("/sendMsg")
    public R<?> sendMsg(@RequestBody @Valid SendMsgDTO sendMsgDTO) {
        if (!RegexValidateUtils.checkCellphone(sendMsgDTO.getPhone())) {
            throw new BusinessException("手机号格式不正确！");
        }

        Integer code = ValidateCodeUtils.generateValidateCode(6);
        //SMSUtils.sendMessage("柚子的健康项目", "SMS_184625591", sendMsgDTO.getPhone(), String.valueOf(code));
        redisTemplate.opsForValue().set(SystemCode.LOGIN + sendMsgDTO.getPhone(),
                String.valueOf(code), 1L, TimeUnit.MINUTES);
        log.info("存入redis中的验证码为：" + code);
        return R.success("短信发送成功！");
    }

    @PostMapping("/login")
    public R<?> login(@RequestBody @Valid UserLoginDTO userLoginDTO, HttpServletRequest request) {
        if (!RegexValidateUtils.checkCellphone(userLoginDTO.getPhone())) {
            throw new BusinessException("手机号格式不正确！");
        }

        String code = (String) redisTemplate.opsForValue().get(SystemCode.LOGIN + userLoginDTO.getPhone());
        if (!Objects.equals(code, userLoginDTO.getCode())) {
            throw new BusinessException("验证码错误！");
        }

        if (StrUtil.isNotBlank(code) && Objects.equals(code, userLoginDTO.getCode())) {
            //验证码通过
            User one = userService.getOne(new LambdaQueryWrapper<User>()
                    .eq(User::getPhone, userLoginDTO.getPhone())
                    .eq(User::getStatus, 1));

            if (Objects.isNull(one)) {
                one = User.builder()
                        .phone(userLoginDTO.getPhone())
                        .status(1)
                        .build();
                userService.save(one);
            }
            request.getSession().setAttribute("user", one.getId());
            //登录成功就删除redis中的验证码(一次性验证码)
            redisTemplate.delete(SystemCode.LOGIN + userLoginDTO.getPhone());
            return R.success(one);
        }
        return R.success("登录失败！");
    }

    @PostMapping("/loginout")
    public R<?> loginOut(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return R.success("登出成功！");
    }
}

